package com.upyun.playdemo;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.upyun.playdemo.activity.PingBanApplication;
import com.upyun.playdemo.auto.config.AutoLayoutConifg;
import com.upyun.playdemo.auto.utils.AutoLayoutHelper;
import com.upyun.playdemo.fragment.AudioFragment;
import com.upyun.playdemo.fragment.BaseView;
import com.upyun.playdemo.fragment.DocFragment;
import com.upyun.playdemo.fragment.HistoryVideoPlaybackFragment;
import com.upyun.playdemo.fragment.RealTimeMonitoringFragment;
import com.upyun.playdemo.fragment.SettingFragment;
import com.upyun.playdemo.fragment.VodVideoStreamingFragment;
import com.upyun.playdemo.mode.MeetingInfo;
import com.upyun.playdemo.utils.Constant;
import com.upyun.playdemo.utils.OPENLOG;
import com.upyun.playdemo.view.ItemIconView;
import com.upyun.upplayer.widget.UpVideoView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;

public class MainActivity extends FragmentActivity {

    private static final String MEETING_WEB_SOCKET_URL = "ws://f117cdh.gnway.cc:81/admin";
    private static final int MEETING_OPEN_STATE = 1;
    private static final int MEETING_CLOSE_STATE = 0;

    private static final List<Integer> ITEM_IDS = new ArrayList<Integer>() {
        {
            add(R.id.monitored_item);
            add(R.id.history_playback_item);
            add(R.id.vod_video_item);
            add(R.id.audio_item);
            add(R.id.doc_item);
            add(R.id.setting_item);
        }
    };

    private static final List<Integer> DEFAULT_ITEM_ICONS = new ArrayList<Integer>() {
        {
            add(R.drawable.default_monitoring);
            add(R.drawable.default_huifang);
            add(R.drawable.default_video);
            add(R.drawable.default_audio);
            add(R.drawable.default_doc);
            add(R.drawable.default_setting);
        }
    };

    private static final List<Integer> PRESS_ITEM_ICONS = new ArrayList<Integer>() {
        {
            add(R.drawable.press_monitoring);
            add(R.drawable.press_huifang);
            add(R.drawable.press_video);
            add(R.drawable.press_audio);
            add(R.drawable.press_doc);
            add(R.drawable.press_setting);
        }
    };

    private final WebSocketConnection mMeetingConnection = new WebSocketConnection();
    ViewPager mViewPager;
    //    MyFragmentPagerAdapter mAdapter;
    DemoPagerAdapter mAdapter;
    List<BaseView> mFragmentList = new ArrayList<BaseView>();
    NetWorkListerReceiver mNetWorkListerReceiver;
    /**
     * !!!! BUG: 防止第一次 界面没有加载，接受到广播，加载起来了，导致的崩溃问题.
     */
    private boolean isUpdate = false;  // 防止界面没有加载，已经在加载数据.

    @InjectView(R.id.bottom_tool_rlay)
    RelativeLayout bottomToolRlay;
    @InjectView(R.id.meeting_video_view)
    UpVideoView meetingVideoView;

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        View view = AutoLayoutHelper.onCreateView(name, context, attrs);
        if (view != null)
            return view;
        return super.onCreateView(name, context, attrs);
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(Constant.UPDATE_NETWORK_ACTION);
        mNetWorkListerReceiver = new NetWorkListerReceiver();
        this.registerReceiver(mNetWorkListerReceiver, filter);
    }

    private void unregisterReceiver() {
        this.unregisterReceiver(mNetWorkListerReceiver);
    }

    public List<BaseView> getmFragmentList() {
        return mFragmentList;
    }

    /**
     * 停止相关的视频和音频.
     */
    public void stopAllVideoAndAudio(int pos) {
        List<BaseView> fragmentList = getmFragmentList();
        for (int i = 0; i < fragmentList.size(); i++) {
            if (i != pos) {
                fragmentList.get(i).stopVideoView();
            }
        }
    }

    @Override
    protected void onDestroy() {
        for (BaseView baseView : mFragmentList) {
            baseView.onDestroy();
        }
        Toast.makeText(getApplicationContext(), "onDestroy", Toast.LENGTH_SHORT).show();
        unregisterReceiver();
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OPENLOG.D("onCreate=====>");
        OPENLOG.initTag("hailongqiu", true); // 初始化LOG信息.
        setContentView(R.layout.activity_main);
        ((PingBanApplication) getApplicationContext()).initRootAddr(); // 初始化服务器地址.
        initPermissionRequest(); // 初始化权限.
        AutoLayoutConifg.getInstance().init(getApplicationContext()); // 初始化自动适配平台.
        int dH = AutoLayoutConifg.getInstance().getDesignHeight();
        int dw = AutoLayoutConifg.getInstance().getDesignWidth();
        OPENLOG.D("分辨率:" + dw + "*" + dH);
        ButterKnife.inject(this);
        initReceiver(); // 初始化网络监听广播.
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        initWebSocketService();
        initAllFragments();
        /* 初始化 viewpager 各个页面 */
        mAdapter = new DemoPagerAdapter();
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(6);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setItemIconBgColor(findViewById(ITEM_IDS.get(position)));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        // 初始化各个VIEW的界面.
        for (BaseView baseView : mFragmentList) {
            baseView.onActivityCreated();
        }
        onClick(findViewById(R.id.monitored_item)); // 设置默认页面.
    }

    private static final String[] PERMISSION_ARRAY = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.READ_PHONE_STATE,
    };

    /**
     * 初始化权限.
     */
    private void initPermissionRequest() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                        250);
//                ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, -250);
            }
        }
    }

    private void initWebSocketService() {
        try {
            mMeetingConnection.connect(MEETING_WEB_SOCKET_URL, mWebSocketHandler);
        } catch (WebSocketException e) {
            e.printStackTrace();
            OPENLOG.E("error:" + e.getMessage());
        }
    }

    private void initAllFragments() {
          /* 实时监控界面 */
        RealTimeMonitoringFragment realTimeMonitoringFragment = RealTimeMonitoringFragment.newInstance(this);
        mFragmentList.add(realTimeMonitoringFragment);
         /* 历史视频回放 */
        HistoryVideoPlaybackFragment historyVideoPlaybackFragment = HistoryVideoPlaybackFragment.newInstance(this);
        mFragmentList.add(historyVideoPlaybackFragment);
        /*  VOD视频点播界面 */
        VodVideoStreamingFragment vodVideoStreamingFragment = VodVideoStreamingFragment.newInstance(this);
        mFragmentList.add(vodVideoStreamingFragment);
        /* 音频 界面 */
        AudioFragment audioFragment = AudioFragment.newInstance(this);
        mFragmentList.add(audioFragment);
        /* 文档 */
        DocFragment docFragment = DocFragment.newInstance(this);
        mFragmentList.add(docFragment);
        /* 设置 */
        SettingFragment settingFragment = SettingFragment.newInstance(this);
        mFragmentList.add(settingFragment);
        /* 加入 view 到列表 */
        for (int i = 0; i < mFragmentList.size(); i++) {
            View rootView = mFragmentList.get(i).onCreateView(getLayoutInflater());
            viewList.add(rootView);
        }
    }

    public void setItemIconBgColor(final View view) {
        ItemIconView itemIconView = (ItemIconView) view;
        int count = bottomToolRlay.getChildCount();
        for (int i = 0; i < count; i++) {
            ItemIconView child = (ItemIconView) bottomToolRlay.getChildAt(i);
            child.setIcon(DEFAULT_ITEM_ICONS.get(i));
            child.setTextColor(Color.WHITE);
        }
        itemIconView.setIcon(PRESS_ITEM_ICONS.get(mViewPager.getCurrentItem()));
        itemIconView.setTextColor(Color.parseColor("#3AC5F2"));
    }

    @Override
    public void onBackPressed() {
    }

    @OnClick({R.id.monitored_item, R.id.history_playback_item, R.id.vod_video_item, R.id.audio_item, R.id.doc_item, R.id.setting_item})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.monitored_item: // 监控.
                mViewPager.setCurrentItem(0);
                mFragmentList.get(0).onRefresh();
                break;
            case R.id.history_playback_item: // 回放
                mViewPager.setCurrentItem(1);
                mFragmentList.get(1).onRefresh();
                break;
            case R.id.vod_video_item: // 视频
                mViewPager.setCurrentItem(2);
                mFragmentList.get(2).onRefresh();
                break;
            case R.id.audio_item: // 音频
                mViewPager.setCurrentItem(3);
                mFragmentList.get(3).onRefresh();
                break;
            case R.id.doc_item: // 文档
                mViewPager.setCurrentItem(4);
                mFragmentList.get(4).onRefresh();
                break;
            case R.id.setting_item: // 设置
                mViewPager.setCurrentItem(5);
                break;
        }
        setItemIconBgColor(view);
    }

    private List<View> viewList = new ArrayList<>();

    /**
     * viewpager 的 adpater.
     */
    class DemoPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return viewList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(viewList.get(position));
        }

        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewList.get(position));
            return viewList.get(position);
        }

    }

    /**
     * 会议websocket.
     */
    WebSocketHandler mWebSocketHandler = new WebSocketHandler() {
        @Override
        public void onOpen() {
            OPENLOG.D("meeting onOpen");
        }

        @Override
        public void onTextMessage(String payload) {
//            OPENLOG.D("payload:" + payload);
            try {
                Gson gson = new Gson();
                MeetingInfo meetingInfo = gson.fromJson(payload, MeetingInfo.class);
                Message msg = mMeetingHandler.obtainMessage();
                msg.obj = meetingInfo;
                mMeetingHandler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
                OPENLOG.E("error:" + e.getMessage());
            }
        }

        @Override
        public void onClose(int code, String reason) {
            OPENLOG.D("meeting onClose code:" + code + " reason:" + reason);
        }

    };

    /**
     * 会议视频界面更新.
     */
    Handler mMeetingHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            MeetingInfo meetingInfo = (MeetingInfo) msg.obj;
            if (meetingInfo != null) {
                String url = meetingInfo.getMeeting_address();
                switch (meetingInfo.getMeeting()) {
                    case MEETING_OPEN_STATE: // 视频会议打开.
                        // 打开播放器播放会议，并且显示出来.
                        if (meetingVideoView.getVisibility() == View.GONE) {
                            stopAllVideoAndAudio(-1); // 停止相关的视频和声音.
                            meetingVideoView.setVisibility(View.VISIBLE);
                            meetingVideoView.setVideoPath(url);
                            meetingVideoView.start();
                        }
                        break;
                    case MEETING_CLOSE_STATE: // 视频会议关闭.
                    default:
                        //  关闭播放器会议，并且隐藏.
                        if (meetingVideoView.getVisibility() == View.VISIBLE) {
                            meetingVideoView.stopPlayback();
                            meetingVideoView.setVisibility(View.GONE);
                            meetingVideoView.start();
                        }
                        break;
                }
            }
        }
    };

    /**
     * 网络状态广播监听.
     */
    public class NetWorkListerReceiver extends BroadcastReceiver {

        private ConnectivityManager mConnectivityManager;
        private NetworkInfo netInfo;

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) || action.equals(Constant.UPDATE_NETWORK_ACTION)) {
                mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable()) {
                    // 网络连接，用BUS发送消息，更新界面.
                    Log.d("hailongqiu", "网络已经连接");
                    // 更新界面.
                    if (isUpdate) {
                        for (BaseView baseView : mFragmentList) {
                            baseView.updateNetWorkView();
                        }
                    }
                    isUpdate = true;
                } else {
                    Toast.makeText(context, "网络断开，请检查网络", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

}
